package com.example.vaccine.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.vaccine.entity.CheckRecords;
import com.example.vaccine.entity.CheckTasks;
import com.example.vaccine.entity.Vaccines;
import com.example.vaccine.mapper.CheckRecordsMapper;
import com.example.vaccine.mapper.CheckTasksMapper;
import com.example.vaccine.mapper.VaccinesMapper;
import com.example.vaccine.service.CheckService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CheckServiceImpl  implements CheckService {
    @Autowired
    private CheckTasksMapper checkTaskMapper;

    @Autowired
    private CheckRecordsMapper checkRecordMapper;

    @Autowired
    private VaccinesMapper vaccineMapper;

    // 查询指定核查员的待核查任务（只查 status=“pending”的）
    public List<Vaccines> getPendingVaccinesByChecker(Integer checkerId) {
        // 先查核查任务
        List<CheckTasks> tasks = checkTaskMapper.selectList(
                new QueryWrapper<CheckTasks>()
                        .eq("checker_id", checkerId)
                        .eq("status", "pending")
        );
        if (tasks.isEmpty()) return Collections.emptyList();

        // 根据任务中的vaccineNumbering查疫苗详细
        List<String> numberingList = tasks.stream()
                .map(CheckTasks::getVaccineNumbering)
                .collect(Collectors.toList());

        return vaccineMapper.selectList(
                new QueryWrapper<Vaccines>().in("numbering", numberingList)
        );
    }

    // 查询指定核查员的已核查记录
    public List<CheckRecords> getCheckedRecordsByChecker(Integer checkerId) {
        return checkRecordMapper.selectList(
                new QueryWrapper<CheckRecords>()
                        .eq("checker_id", checkerId)
                        .orderByDesc("check_time")
        );
    }

    // 提交核查结果：插入核查记录，更新核查任务状态
    @Transactional
    public void submitCheckResult(Integer checkerId, String vaccineNumbering, Boolean flag, String reason) {
        // 插入核查记录，checkNumber可以设计为该疫苗核查次数+1
        Integer maxCheckNumber = checkRecordMapper.selectObjs(
                new QueryWrapper<CheckRecords>()
                        .select("MAX(check_number)")
                        .eq("vaccine_numbering", vaccineNumbering)
        ).stream().findFirst().map(o -> (Integer) o).orElse(0);
        LocalDateTime now = LocalDateTime.now();
        Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());

        CheckRecords record = new CheckRecords();
        record.setVaccineNumbering(vaccineNumbering);
        record.setCheckerId(checkerId);
        record.setFlag(flag);
        record.setReason(reason);
        record.setCheckNumber(maxCheckNumber + 1);
        record.setCheckTime(date);
        record.setCreatedAt(date);
        record.setUpdatedAt(date);
        checkRecordMapper.insert(record);

        // 更新核查任务状态为 completed
        UpdateWrapper<CheckTasks> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("checker_id", checkerId)
                .eq("vaccine_numbering", vaccineNumbering)
                .set("status", "completed");
        checkTaskMapper.update(null, updateWrapper);
    }
}
